#!/usr/bin/env python3
# Single purpose HTTP server
# - serves files specified as arguments in order of appearance

import os
import sys
import http.server
import cgi

class Handler(http.server.BaseHTTPRequestHandler):
    def do_POST(self):
#        self.send_response(200)
#        self.send_header("Content-type", "text/xml")
#        self.end_headers()

#        print(self.rfile.read(int(self.headers.getheader('content-length'))))

        if 'attachments' in self.path:
            #content_length = int(self.headers['Content-Length'])
            #file_content = self.rfile.read(content_length)
            form = cgi.FieldStorage(
                 fp=self.rfile,
                 headers=self.headers,
                 environ={"REQUEST_METHOD": "POST",
                          "CONTENT_TYPE": self.headers['Content-Type']})

            uploaded_file = form.getvalue("file")
            if uploaded_file:
                with open('data.tar.gz', "wb") as fh:
                    fh.write(uploaded_file)

        response = self.dummy_response
        if not self.filelist:
            print('No more files to serve - sending dummy response')
        else:
            response = self.filelist.pop()
        self.wfile.write(response)


PORT = 12345
print("Serving at port", PORT)

filelist = []
for file in sys.argv[1:]:
    if os.path.isfile(file):
        print("Adding file", file)
        with open(file, "rb") as f:
            filelist.append(f.read())

filelist.reverse()
Handler.filelist = filelist
Handler.dummy_response = open("dummy", "rb").read()
httpd = http.server.HTTPServer(("", PORT), Handler)
httpd.serve_forever()
